﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LOPA.Actions;
using Model;

namespace LOPA
{
    public partial class MainForm : Form{

        public static MainForm mainForm = null;
        public static string currentProject = string.Empty;
        private DataTable dtTree = null;
        private DataView dv = null;
        private string _saveFilePath = string.Empty;

        public MainForm(){
            mainForm = this;
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            CenterToScreen();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            
        }

        private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!currentProject.Equals(string.Empty)) {
                MessageBox.Show("项目已经创建！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                return;
            }
            if(new ProjectDetailsForm().ShowDialog() != DialogResult.OK) {
                return;
            }
            if(!currentProject.Equals(string.Empty)) {
                CreateProjectTree();
                
            }          
            _saveFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\LOPA Project\\"+currentProject+"\\"+currentProject+".lpa";
        }

        private void AddImages(TreeNodeCollection node) {
            foreach (TreeNode treeNode in node) {
                if (treeNode.Nodes.Count != 0) 
                    AddImages(treeNode.Nodes);
                if (treeNode.Text.Equals(currentProject))
                {
                    treeNode.ImageIndex = 0;
                    treeNode.SelectedImageIndex = 0;
                }
                else if (treeNode.Text.Equals("LOPA小组"))
                {
                    treeNode.ImageIndex = 1;
                    treeNode.SelectedImageIndex = 1;
                }
                else if (treeNode.Text.Equals("PSI清单"))
                {
                    treeNode.ImageIndex = 2;
                    treeNode.SelectedImageIndex = 2;
                }
                else if (treeNode.Text.Equals("图纸清单"))
                {
                    treeNode.ImageIndex = 3;
                    treeNode.SelectedImageIndex = 3;
                }
                else if (treeNode.Text.Equals("风险标准") || treeNode.Text.Equals("引发事件频率") || treeNode.Text.Equals("独立保护层失效频率"))
                {
                    treeNode.ImageIndex = 6;
                    treeNode.SelectedImageIndex = 6;
                }
                else if (treeNode.Text.Equals("LOPA分析表"))
                {
                    treeNode.ImageIndex = 4;
                    treeNode.SelectedImageIndex = 4;
                }
                else if (treeNode.Parent.Text.Equals("LOPA分析表"))
                {
                    treeNode.ImageIndex = 5;
                    treeNode.SelectedImageIndex = 5;
                }
            }
        }

        public TreeView ProjectTree{
            get { return tvProject; }
            set { tvProject = value; }
        }

        public TabControl TabPages{
            set { tcWorkSpace = value; }
            get { return tcWorkSpace; }
        }

        public string SaveFilePath {
            get { return _saveFilePath; }
            set { _saveFilePath = value; }
        }

       private void tvProject_AfterSelect(object sender, TreeViewEventArgs e){
            e.Node.Expand();
            TreeNode treeNode = tvProject.SelectedNode;

            if (treeNode.Text.Equals(currentProject))
                return;
            if (treeNode.Text.Equals("LOPA分析表")){
                treeNode.ContextMenuStrip = cmsTreeView;
            }

            if (tcWorkSpace.TabPages.ContainsKey(treeNode.Text))
            {
                for (int i = 0; i < tcWorkSpace.TabPages.Count; i++)
                {
                    if (treeNode.Text.Equals(tcWorkSpace.TabPages[i].Name))
                    {
                        tcWorkSpace.SelectedIndex = i;
                        break;
                    }
                }
            }
            else if (treeNode.Parent.Text.Equals("LOPA分析表"))
            {
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                LOPAWorkNode workNode = Program.Workspace.GetWorkNodeByNodeName(treeNode.Text);
                LopaWorkPage workPage = new LopaWorkPage(workNode);
                tabPage.Controls.Add(workPage);
                workPage.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }
            else if (treeNode.Text.Equals("图纸清单"))
            {
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                PidPage pidPage = new PidPage();
                tabPage.Controls.Add(pidPage);
                pidPage.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }

            else  if (treeNode.Text.Equals("PSI清单"))
            {
               TabPage tabPage = new TabPage(treeNode.Text);
               tabPage.Name = treeNode.Text;
               PSIPage psiPage = new PSIPage();
               tabPage.Controls.Add(psiPage);
               psiPage.Dock = DockStyle.Fill;
               tcWorkSpace.TabPages.Add(tabPage);
               tcWorkSpace.SelectedTab = tabPage;
            }
            else if (treeNode.Text.Equals("LOPA小组"))
            {
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                HazopTeamPage3 hazopTeam = new HazopTeamPage3();
                tabPage.Controls.Add(hazopTeam);
                hazopTeam.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }
            else if (treeNode.Text.Equals("风险标准")){
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                RiskCriteria riskMatrixPage = new RiskCriteria();
                tabPage.Controls.Add(riskMatrixPage);
                riskMatrixPage.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }
            else if (treeNode.Text.Equals("引发事件频率"))
            {
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                EventFrequence eventFrequence = new EventFrequence();
                tabPage.Controls.Add(eventFrequence);
                eventFrequence.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }
            else if (treeNode.Text.Equals("独立保护层失效频率"))
            {
                TabPage tabPage = new TabPage(treeNode.Text);
                tabPage.Name = treeNode.Text;
                PfdFrequence pfdFrequence = new PfdFrequence();
                tabPage.Controls.Add(pfdFrequence);
                pfdFrequence.Dock = DockStyle.Fill;
                tcWorkSpace.TabPages.Add(tabPage);
                tcWorkSpace.SelectedTab = tabPage;
            }
        }

        private void tcWorkSpace_MouseDown(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right){
                for(int i = 0; i < tcWorkSpace.TabPages.Count; i++){
                    TabPage tabPage = tcWorkSpace.TabPages[i];
                    if(tcWorkSpace.GetTabRect(i).Contains(new Point(e.X,e.Y))){
                        tcWorkSpace.SelectedTab = tabPage;
                        tcWorkSpace.ContextMenuStrip = cmsTapPage;
                        break;
                    }
                } 
            }
        }

        private void tcWorkSpace_MouseLeave(object sender, EventArgs e){
            tcWorkSpace.ContextMenuStrip = null;
        }

        private void closeTabMenuItem_Click(object sender, EventArgs e){
            string[] s = { "LOPA小组", "图纸清单", "PSI清单", "风险标准", "引发事件频率", "独立保护层失效频率" };
            string name = tcWorkSpace.SelectedTab.Text;
            if (!s.Contains(name))
            {
                foreach (var control in tcWorkSpace.SelectedTab.Controls)
                {
                    if (control.GetType() == typeof(LopaWorkPage))
                    {
                        LopaWorkPage page = (LopaWorkPage)control;
                        if(page.TbxAdvice.Enabled == false){
                            tcWorkSpace.SelectedTab.Dispose();
                            return;
                        }
                        else{
                            break;
                        }
                    }
                }
               if(new WarringForm("页面尚未保存，是否需要保存？").ShowDialog() ==DialogResult.OK){
                   foreach (var control in tcWorkSpace.SelectedTab.Controls)
                   {
                       if (control.GetType() == typeof(LopaWorkPage))
                       {
                           LopaWorkPage p = (LopaWorkPage)control;
                           p.SaveWithoutRemider();
                           break;
                       }
                   }
                   Program.Workspace.SaveProject(_saveFilePath);
                   MessageBox.Show("保存成功！");
                   tcWorkSpace.SelectedTab.Dispose();
                   return;
               }
               else
               {
                   tcWorkSpace.SelectedTab.Dispose();
               }
            }
            else
            {
                tcWorkSpace.SelectedTab.Dispose();
            }   
          //  tcWorkSpace.SelectedTab.Hide();
          //  tcWorkSpace.TabPages["PSI清单"].Parent = null;
            //     tcWorkSpace.TabPages.Remove(tcWorkSpace.SelectedTab);
        }

        private void chemicalLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChemicalLibraryForm chemicalLibraryForm = new ChemicalLibraryForm();
            chemicalLibraryForm.Show();
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CreateProjectTree()
        {
            CreateTable();
            CreateTree();
            ProjectTree.ImageList = _imgProject;
            AddImages(ProjectTree.Nodes);
        }

        private void CreateTable()
        {
            dtTree = new DataTable("ProjectTree");
            dtTree.Columns.Add(new DataColumn("TypeID", typeof(int)));
            dtTree.Columns.Add(new DataColumn("TypeName", typeof(string)));
            dtTree.Columns.Add(new DataColumn("TypeParentID", typeof(int)));

            dtTree.Rows.Add(new object[] { 1, currentProject, 0 });
            dtTree.Rows.Add(new object[] { 2, "LOPA小组", 1 });
            dtTree.Rows.Add(new object[] { 3, "PSI清单", 1 });
            dtTree.Rows.Add(new object[] { 4, "图纸清单", 1 });
            dtTree.Rows.Add(new object[] { 5, "LOPA分析表", 1 });
            dtTree.Rows.Add(new object[] { 6, "风险标准", 1 });
            dtTree.Rows.Add(new object[] { 7, "引发事件频率", 1 });
            dtTree.Rows.Add(new object[] { 8, "独立保护层失效频率", 1 });
            //dtTree.Rows.Add(new object[] { 7, "通用建议", 5 });

        }

        private void CreateTree()
        {
            dv = dtTree.DefaultView;
            dv.Sort = "TypeParentID ASC";
            DataRowView[] arrDRV = dv.FindRows(0);
            if (arrDRV.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDRV)
            {
                tnNew = MainForm.mainForm.ProjectTree.Nodes.Add(drv.Row["TypeName"].ToString());
                tnNew.Tag = drv.Row["TypeID"].ToString();
                tnNew.Name = drv.Row["TypeName"].ToString();
                CreateTreeNode(ref tnNew);
            }
        }

        private void CreateTreeNode(ref TreeNode tnParent)
        {
            DataRowView[] arrDRV = dv.FindRows(tnParent.Tag);
            if (arrDRV.Length == 0)
                return;
            TreeNode tnNew = null;
            foreach (DataRowView drv in arrDRV)
            {
                tnNew = tnParent.Nodes.Add(drv.Row["TypeName"].ToString());
                tnNew.Tag = drv.Row["TypeID"].ToString();
                tnNew.Name = drv.Row["TypeName"].ToString();
                CreateTreeNode(ref tnNew);
            }
        }

        private void addNodeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(Program.Workspace.LopaProject.PidList.Count == 0) {
                MessageBox.Show("未发现PID列表，请先创建!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (tvProject.SelectedNode != null){
                AddNodeForm addNodeForm = new AddNodeForm();
                addNodeForm.treeViewAddNode += new AddNodeForm.treeViewAddNodeEventHandler(addNodeForm_treeViewAddNode);
                addNodeForm.ShowDialog();
            }
        }

        private void addNodeForm_treeViewAddNode(string name, string pidList)
        {
            TreeNode treeNode = new TreeNode(name);
            treeNode.ImageIndex = 5;
            treeNode.SelectedImageIndex = 5;
            tvProject.SelectedNode.Nodes.Add(treeNode);

          //  tvProject.SelectedNode = treeNode;
            TabPage tabPage = new TabPage(treeNode.Text);
            tabPage.Name = treeNode.Text;
         //   WorkPage workPage = new WorkPage(Program.Workspace.project.ProjectDetails.ProjectName, name, DateTime.Today, GetTotalNodeCount().ToString(), pidList, Program.Workspace.project.ProjectDetails.ProjectDesc);
            LOPAWorkNode workNode = new LOPAWorkNode(Program.Workspace.LopaProject.ProjectDetails.ProjectName,name,
                                             GetTotalNodeCount().ToString(), DateTime.Today.ToShortDateString(), pidList);
            LopaWorkPage workPage = new LopaWorkPage(workNode);
            Program.Workspace.AddNewWorkNode(workNode);
            tabPage.Controls.Add(workPage);
            workPage.Dock = DockStyle.Fill;
            tcWorkSpace.TabPages.Add(tabPage);
            tcWorkSpace.SelectedTab = tabPage;
        }

        private int GetTotalNodeCount(){
            return tvProject.SelectedNode.Nodes.Count;
        }

        /*private void saveSinglePage_Click(object sender, EventArgs e){
            if (tcWorkSpace.TabPages.Count == 0) {
                MessageBox.Show("没有可保存的页面");
                return;
            }
            string tapName = tcWorkSpace.SelectedTab.Text;
            if (tapName.Equals("LOPA小组")) {
                foreach (var control in tcWorkSpace.SelectedTab.Controls) {
                    if (control.GetType() == typeof(HazopTeamPage2)) {
                        HazopTeamPage2 page = (HazopTeamPage2) control;
                        page.btnSave_Click(sender,e);
                    }
                }
            }
            else if (tapName.Equals("PSI清单")) {
                foreach (var control in tcWorkSpace.SelectedTab.Controls)
                {
                    if (control.GetType() == typeof(PSIPage))
                    {
                        PSIPage page = (PSIPage)control;
                        page.btnSave_Click(sender, e);
                    }
                }
            }
            else if (tapName.Equals("图纸清单")) {
                foreach (var control in tcWorkSpace.SelectedTab.Controls)
                {
                    if (control.GetType() == typeof(PidPage))
                    {
                        PidPage page = (PidPage)control;
                        page.btnSave_Click(sender, e);
                    }
                }
            }
            else if (tapName.Equals("风险矩阵")) {
                foreach (var control in tcWorkSpace.SelectedTab.Controls)
                {
                    if (control.GetType() == typeof(RiskMatrixPage))
                    {
                        RiskMatrixPage page = (RiskMatrixPage)control;
                        page.btnSave_Click(sender, e);
                    }
                }
            }
            else {
                //save worknodes
                WorkNode workNode = Program.Workspace.GetWorkNodeByNodeName(tapName);
          //      List<WorkNodeItem> list = new List<WorkNodeItem>();
                if (workNode == null){
                    MessageBox.Show(workNode.NodeName + " 节点未找到！","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                foreach (var control in tcWorkSpace.SelectedTab.Controls)
                {
                    if (control.GetType() == typeof(WorkPage))
                    {
                        WorkPage workPage = (WorkPage)control;
                    //    list = new List<WorkNodeItem>((BindingList<WorkNodeItem>)((WorkPage)control).DgvWorkArea.DataSource);
                        workNode.NodeName = workPage.LblNodeName.Text;
                        workNode.NodeNum = workPage.LblNodeNum.Text;
                        workNode.ProjectName = workPage.LblProjectName.Text;
                        workNode.SessionDate = workPage.SessionDate.Value;
                        workNode.PidList = workPage.LblPidNum.Text;
                        workNode.TecDesc = workPage.TbxTechDescription.Text;
                    //    workNode.WorkNodeItemList = list;
                        break;
                    }
                }
                Program.Workspace.SaveProject(SaveFilePath);
                MessageBox.Show(workNode.NodeName+"保存成功!");
            }
           
           
        }*/

        private void eventLibraryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EventLibraryForm eventForm = new EventLibraryForm();
            eventForm.Show();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentProject.Equals(string.Empty))
            {
                MessageBox.Show("没有可保存的项目!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Project Data(*.lpa)|";
            dialog.Title = "保存项目";
            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dialog.CheckPathExists = true;
            dialog.ValidateNames = true;
            dialog.AddExtension = true;
            dialog.DefaultExt = "lpa";
            if (dialog.ShowDialog() == DialogResult.OK) {
                _saveFilePath = dialog.FileName;
                Program.Workspace.SaveProject(dialog.FileName);
                MessageBox.Show("项目保存成功");
            }
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentProject.Equals(string.Empty))
            {
                MessageBox.Show("没有导出的项目!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Excel 2003(*.xls)|*.xls|Excel 2007(*.xlsx)|*.xlsx|Excel 2010(*.xlsx)|*.xlsx";
            dialog.FilterIndex = 0;
            dialog.Title = "保存项目";
            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dialog.CheckPathExists = true;
            dialog.ValidateNames = true;
            dialog.AddExtension = true;
            dialog.DefaultExt = "xls";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //Program.Workspace.ExportToExcel(dialog.FileName,Program.Workspace.project,Program.Workspace.GetHideColumns());

              //  MessageBox.Show("Excel数据成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                new ExcelExportAction(dialog.FileName,Program.Workspace.LopaProject).RunInProgress();
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!currentProject.Equals(string.Empty)) {
                MessageBox.Show("项目已经创建，不能重复导入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "打开项目文件";
            dialog.Filter = "Project Data(*.lpa)|*.lpa";
            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dialog.CheckPathExists = true;
            dialog.CheckFileExists = true;
            dialog.ValidateNames = true;
            LopaProject project = null;
            if (dialog.ShowDialog() == DialogResult.OK){
                if (!dialog.FileName.Contains(".lpa"))
                {
                    MessageBox.Show("不是LOPA项目文件，请重新导入!", "项目文件导入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                _saveFilePath = dialog.FileName;
                project = Program.Workspace.OpenProject(dialog.FileName);
            }
            if (project != null){
                createTreeView(project);
            }
        }

        private void createTreeView(LopaProject project){
            currentProject = project.ProjectDetails.ProjectName;
            CreateProjectTree();
           //create all worknodes
            foreach (LOPAWorkNode workNode in project.LopaWorkNodeList) {
                ProjectTree.Nodes[currentProject].Nodes["LOPA分析表"].Nodes.Add(workNode.EventName);
            }
            AddImages(ProjectTree.Nodes);
        }

        private void createNode_Click(object sender, EventArgs e) {
            if (currentProject.Equals(string.Empty)) {
                MessageBox.Show("项目为空，请首先创建项目!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ProjectTree.SelectedNode = ProjectTree.Nodes[currentProject].Nodes["LOPA分析表"];
            addNodeToolStripMenuItem_Click(sender, e);
        }

        private void newProject_Click(object sender, EventArgs e) {
            newProjectToolStripMenuItem_Click(sender, e);
        }

        private void openProject_Click(object sender, EventArgs e) {
            openToolStripMenuItem_Click(sender, e);
        }

        private void saveAllStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentProject.Equals(string.Empty))
            {
                MessageBox.Show("没有可保存的项目!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (_saveFilePath.Equals(string.Empty))
            {
                MessageBox.Show("保存目录为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            foreach (TabPage page in tcWorkSpace.TabPages)
            {
                if (tcWorkSpace.TabPages.Count == 0)
                {
                    MessageBox.Show("没有可保存的页面");
                    return;
                }
                string tapName = page.Text;
                switch (tapName)
                {
                    case "LOPA小组": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(HazopTeamPage3))
                            {
                                HazopTeamPage3 p = (HazopTeamPage3)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    case "PSI清单": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(PSIPage))
                            {
                                PSIPage p = (PSIPage)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    case "图纸清单": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(PidPage))
                            {
                                PidPage p = (PidPage)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    case "风险标准": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(RiskCriteria))
                            {
                                RiskCriteria p = (RiskCriteria)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    case "引发事件频率": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(EventFrequence))
                            {
                                EventFrequence p = (EventFrequence)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    case "独立保护层失效频率": foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(PfdFrequence))
                            {
                                PfdFrequence p = (PfdFrequence)control;
                                p.SaveWithoutRemider();
                            }
                        }
                        break;
                    default:
                        foreach (var control in page.Controls)
                        {
                            if (control.GetType() == typeof(LopaWorkPage))
                            {
                                LopaWorkPage p = (LopaWorkPage)control;
                                p.SaveWithoutRemider();
                                break;
                            }
                        }
                        break;
                }
            }
            Program.Workspace.SaveProject(_saveFilePath);
            MessageBox.Show("项目保存成功!");

        }

        private void editGuideWordToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void exportToExcel_Click(object sender, EventArgs e) {
            exportToolStripMenuItem_Click(sender, e);
        }

        private void saveAll_Click(object sender, EventArgs e){
            saveAllStripMenuItem_Click(sender, e);
        }

        private void tvProject_Click(object sender, EventArgs e) {
            if (ProjectTree.SelectedNode != null)
            {
                ProjectTree.SelectedNode.Expand();
                TreeNode treeNode = tvProject.SelectedNode;

                if (treeNode.Text.Equals(currentProject))
                    return;
                if (treeNode.Text.Equals("LOPA分析表"))
                {
                    treeNode.ContextMenuStrip = cmsTreeView;
                }

                if (tcWorkSpace.TabPages.ContainsKey(treeNode.Text))
                {
                    for (int i = 0; i < tcWorkSpace.TabPages.Count; i++)
                    {
                        if (treeNode.Text.Equals(tcWorkSpace.TabPages[i].Name))
                        {
                            tcWorkSpace.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else if (treeNode.Parent.Text.Equals("LOPA分析表"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    LOPAWorkNode workNode = Program.Workspace.GetWorkNodeByNodeName(treeNode.Text);
                    LopaWorkPage workPage = new LopaWorkPage(workNode);
                    tabPage.Controls.Add(workPage);
                    workPage.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
                else if (treeNode.Text.Equals("图纸清单"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    PidPage pidPage = new PidPage();
                    tabPage.Controls.Add(pidPage);
                    pidPage.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }

                else if (treeNode.Text.Equals("PSI清单"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    PSIPage psiPage = new PSIPage();
                    tabPage.Controls.Add(psiPage);
                    psiPage.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
                else if (treeNode.Text.Equals("LOPA小组"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    HazopTeamPage3 hazopTeam = new HazopTeamPage3();
                    tabPage.Controls.Add(hazopTeam);
                    hazopTeam.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
                else if (treeNode.Text.Equals("风险标准"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    RiskCriteria riskCriteria = new RiskCriteria();
                    tabPage.Controls.Add(riskCriteria);
                    riskCriteria.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
                else if (treeNode.Text.Equals("引发事件频率"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    EventFrequence eventFrequence = new EventFrequence();
                    tabPage.Controls.Add(eventFrequence);
                    eventFrequence.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
                else if (treeNode.Text.Equals("独立保护层失效频率"))
                {
                    TabPage tabPage = new TabPage(treeNode.Text);
                    tabPage.Name = treeNode.Text;
                    PfdFrequence pfdFrequence = new PfdFrequence();
                    tabPage.Controls.Add(pfdFrequence);
                    pfdFrequence.Dock = DockStyle.Fill;
                    tcWorkSpace.TabPages.Add(tabPage);
                    tcWorkSpace.SelectedTab = tabPage;
                }
            }  
        }

        private void tvProject_MouseDown(object sender, MouseEventArgs e)
        {
            if ((sender as TreeView) != null) {
                ProjectTree.SelectedNode = ProjectTree.GetNodeAt(e.X, e.Y);
            }
            if (tcWorkSpace.SelectedTab == null)
            {
                return;
            }
            string name = tcWorkSpace.SelectedTab.Name;
            
//            if (name.Equals("图纸清单") || name.Equals("PSI清单") || name.Equals("Hazop小组") || name.Equals("风险矩阵"))
//                editColToolStripMenuItem.Enabled = false;
//            else
//                editColToolStripMenuItem.Enabled = true;
        }

//        private void tcWorkSpace_Selected(object sender, TabControlEventArgs e){
//            if (e.TabPage == null){
//                return;
//            }
//            string name = e.TabPage.Name;
//            if (name.Equals("图纸清单") || name.Equals("PSI清单") || name.Equals("Hazop小组") || name.Equals("风险矩阵"))
//                editColToolStripMenuItem.Enabled = false;
//            else
//                editColToolStripMenuItem.Enabled = true;
//        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm();
            aboutForm.ShowDialog();
        }

        public TabControl TcWorkSpace{
            get { return tcWorkSpace; }
            set { tcWorkSpace = value; }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!currentProject.Equals(string.Empty))
            {
                DialogResult dr = MessageBox.Show("项目是否需要保存？", "确认保存", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    saveAllStripMenuItem_Click(sender, e);
                }
            }
        }
    }
}
